'use strict';
const fs = require('fs');
const path = require('path');

const Controller = require('egg').Controller;
/**
  * @controller FileController (上传File文件的Controller)
  */
class UploadForFileController extends Controller {
/**
   * @summary 上传文件
   * @description 上传文件
   * @router post /api/uploadFile
   * @request formData file *file 文件
   * @response 200 uploadResponse  返回结果。
   */
  async upload() {
    const { ctx } = this;
    // console.log(ctx.request.body);
    const file = ctx.request.files[0];
    const fileData = fs.readFileSync(file.filepath);
    const base64Str = Buffer.from(fileData, 'binary').toString('base64');
    const bufferData = Buffer.from(base64Str, 'base64');
    // 获取当前日期，用于文件夹创建
    const dirName = ctx.helper.formatTime(new Date());
    // 指定上传路径
    const uploadBasePath = '../public/uploadForFile';
    // 文件重命名
    const filename = `${ctx.helper.getUUID()}${path.extname(file.filename)}`;
    const dir = path.join(__dirname, uploadBasePath, dirName);
    const src = path.join(__dirname, uploadBasePath, dirName, filename);
    // 判断是否存在该文件夹，不存在则创建。
    if (!fs.existsSync(dir)) fs.mkdirSync(dir);
    try {
      await fs.writeFileSync(src, bufferData);
      ctx.status = 200;
      ctx.body = {
        filename,
        url: `/public/uploadForFile/${dirName}/${filename}`,
      };
    } catch (e) {
      ctx.status = 500;
      ctx.body = { msg: '上传文件失败' };
    }
  }
}

module.exports = UploadForFileController;
